FormSerializeUtil   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 42
rs 10
wmc 6

2 Functions

Rating   Name   Duplication   Size   Complexity  
A serialize 0 12 3
A serializeJson 0 9 3
1
import Iterator from 'src/helper/iterator.helper';
2
3
/**
4
 * This utility serializes a form via the FormData class
5
 *
6
 * @package content
7
 */
8
export default class FormSerializeUtil {
9
10
    /**
11
     * serializes a form
12
     *
13
     * @param {HTMLFormElement} form
14
     * @param {boolean} strict
15
     *
16
     * @returns {*}
17
     */
18
    static serialize(form, strict = true) {
19
20
        if (form.nodeName !== 'FORM') {
21
            if (strict) {
22
                throw new Error('The passed element is not a form!');
23
            }
24
25
            return {};
26
        }
27
28
        return new FormData(form);
29
    }
30
31
    /**
32
     *
33
     * serializes the form and returns
34
     * its data as json
35
     *
36
     * @param {HTMLFormElement} form
37
     * @param {boolean} strict
38
     * @returns {*}
39
     */
40
    static serializeJson(form, strict = true) {
41
        const formData = FormSerializeUtil.serialize(form, strict);
42
        if (formData === {}) return formData;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
43
        const json = {};
44
45
        Iterator.iterate(formData, (value, key) => json[key] = value);
46
47
        return json;
48
    }
49
}
50